#!/bin/sh /etc/rc.common

START=85
NAME=haproxy-tcp

genline_srv(){
	line="$1"
	hash="$(echo -n $line | md5sum | cut -c1-6)"
	hash="$(echo -n $line | tr -d '\t ' | cut -c1-8)__$hash"
	echo "    server $hash  $line" | tr -d "\'"
}

boot() {
	local delay=$(uci -q get $NAME.general.startup_delay)
	(sleep ${delay:-0} && start >/dev/null 2>&1) &
	return 0
}

start() {
	enable=$(uci -q get $NAME.general.enable)
	[ "$enable" = 1 ] || return 0
	listen=$(uci -q get $NAME.general.listen)
	admin_stats=$(uci -q get $NAME.general.admin_stats)
	retries=$(uci -q get $NAME.general.retries)
	timeout=$(uci -q get $NAME.general.timeout)
	upstreams=$(uci -q get $NAME.general.upstreams)

	mkdir -p /var/etc
	cat <<-EOF > /var/etc/$NAME.cfg
	global
	    nbproc 2

	defaults
	    mode tcp
	    retries ${retries:-2}
	    timeout connect ${timeout:-1000}

	listen admin_stats
	    bind 0.0.0.0:${admin_stats:-7777}
	    mode http
	    stats uri /
	    stats refresh 10s

	frontend tcp-in
	    bind ${listen:-0.0.0.0:6666}
	    default_backend tcp-out

	backend tcp-out
		$(	if [ 0 -lt $(grep -c weight /etc/config/$NAME) ]; then
				echo "    balance static-rr"
				sed -n 's/.*upstreams[\t ]*//p' /etc/config/$NAME |
				while read upstream; do
					genline_srv "$upstream"
				done
			else
				for upstream in $upstreams; do
				genline_srv "$upstream"
				done
			fi
		)

EOF

	/usr/sbin/$NAME -q -D -f /var/etc/$NAME.cfg -p /var/run/$NAME.pid
}

kill_all() {
	kill -9 $(pgrep -f $@) >/dev/null 2>&1
}

stop() {
	kill_all "$NAME.pid"
	rm -rf /var/etc/$NAME.cfg
}
